<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\Auth;
use App\Models\Customer;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Laravel\Passport\Client;
use GuzzleHttp\Client as Gclient;
use Validator;
class AuthenticateController extends ApiController
{
    use AuthenticatesUsers;

    public function username()
    {
        return 'user_name';
    }

//    protected function guard()
//    {
//        return auth()->guard('api');
//    }

    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'user_password');
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_name'    => 'required',
            'user_password' => 'required',
        ]);
        if ($validator->fails()) {
            $request->request->add([
                'errors' => $validator->errors()->toArray(),
                'code' => 401,
            ]);
            return $this->sendFailedLoginResponse($request);
        }

        $credentials = $this->credentials($request);

        if (Auth::guard('api')->attempt($credentials, $request->has('remember'))) {
            return $this->sendLoginResponse($request);
        }

    }

    public function authenticateClient(Request $request)
    {
        $credentials = $this->credentials($request);

        $password_client = Client::query()->where('password_client',1)->latest()->first();
        $params = [
            'grant_type' => 'password',
            'client_id' => $password_client->id,
            'client_secret' => $password_client->secret,
            'username' => $credentials['user_name'],
            'password' => $credentials['user_password'],
            'scope' => ''
        ];
        $client = new Gclient();
        $url = request()->root() . '/api/oauth/token';
        $respond = $client->request('POST', $url, ['form_params' => $params]);
        return $respond;
    }



    protected function authenticated(Request $request)
    {
        return $this->authenticateClient($request);
    }

    protected function sendLoginResponse(Request $request)
    {
        $this->clearLoginAttempts($request);

        return $this->authenticated($request);
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        $msg = $request['errors'];
        $code = $request['code'];
        return $this->setStatusCode($code)->failed($msg);
    }

}
